package org.deyang.tools.amazon.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.deyang.tools.amazon.pojos.PriceInformation;
import org.w3c.dom.Element;

public class PriceUtils {
	
	public static PriceInformation getCurrentLowPrice(Element itemEle, boolean checkWebPagePrice){
		String price = "";
		String priceAmount = "";
		PriceInformation currentPrice = new PriceInformation();
		boolean isPriceValid = true;
		Element offerElement = AmazonXMLProcessor.getDefaultChildNode(AmazonXMLProcessor.getDefaultChildNode(itemEle, "Offers"),"Offer");
		String itemFormat = AmazonXMLProcessor.getDefaultChildNodeValue(AmazonXMLProcessor.getDefaultChildNode(itemEle, "ItemAttributes"),"Format");
		if (offerElement == null && !itemFormat.equals("Kindle eBook")){
			return currentPrice;
		}
		String offerMerchant = AmazonXMLProcessor.getDefaultChildNodeValue(AmazonXMLProcessor.getDefaultChildNode(offerElement, "Merchant"),"Name");
		String offerCondition = AmazonXMLProcessor.getDefaultChildNodeValue(AmazonXMLProcessor.getDefaultChildNode(offerElement, "OfferAttributes"),"Condition");
		Element offerPrice = AmazonXMLProcessor.getDefaultChildNode(AmazonXMLProcessor.getDefaultChildNode(offerElement, "OfferListing"),"Price");
		
		if (offerPrice == null || offerCondition == null || !offerCondition.equals("New")){
			//if cannot find a price in offers element, then try to get it from LowestNewPrice element
			Element lowNewPriceElement =  AmazonXMLProcessor.getDefaultChildNode(AmazonXMLProcessor.getDefaultChildNode(itemEle, "OfferSummary"), "LowestNewPrice");
			offerPrice = lowNewPriceElement;
		}
		
		price = AmazonXMLProcessor.getDefaultChildNodeValue(offerPrice,"FormattedPrice");
		priceAmount = AmazonXMLProcessor.getDefaultChildNodeValue(offerPrice,"Amount");
		if (priceAmount != null && !priceAmount.trim().equals("")){
			try {
				//Check whether the price amount returned by AWS is a valid value
				Integer.parseInt(AmazonXMLProcessor.getDefaultChildNodeValue(offerPrice,"Amount"));
				if (offerMerchant.startsWith("Amazon")){
					currentPrice.setAmazonPrice(price);
					currentPrice.setAmazonPriceAmount(priceAmount);
					currentPrice.setAmazonPriceAvailable(true);
					//if amazon is provide the lowest offer for new, then don't conside any other third party ones
					return currentPrice;
				}else{
					currentPrice.setThirdPartyPrice(price);
					currentPrice.setThirdPartyPriceAmount(priceAmount);
					currentPrice.setThirdPartyPriceAvailable(true);
				}
			}catch (Exception e){
				isPriceValid = false;
			}
		}else{
			isPriceValid = false;
		}
		
		//If the price from AWS is not valid, then try to get it from web page
		if (!isPriceValid || (checkWebPagePrice && !currentPrice.isAmazonPriceAvailable())){
			//This url should be a url point try to point to amazon.com self selling item
			//String url = "http://www.amazon.com/gp/product/" + AmazonXMLProcessor.getDefaultChildNodeValue(itemEle,"ASIN");
			String url = "http://www.amazon.com/gp/aw/d/" + AmazonXMLProcessor.getDefaultChildNodeValue(itemEle,"ASIN") + "?sp=1&m=ATVPDKIKX0DER";
			try {
				URL producturl = new URL(url);
				StringWriter writer = new StringWriter();
				IOUtils.copy(producturl.openStream(), writer);
				String amazonResp = writer.toString();
				//String regex = "(?<=\\<b\\sclass\\=\\\"priceLarge\\\"\\>)\\$\\d+\\.\\d{2}";
				String regex = "(?<=\\<b\\>Price:\\<\\/b\\>&nbsp;)\\$\\d+\\.\\d{2}";
				Pattern p = Pattern.compile(regex);  
				Matcher m = p.matcher(amazonResp);  
				if (m.find()){
					price = m.group();
					priceAmount = getPriceAmount(price);
					if (amazonResp.indexOf("Ships, sold by: Amazon.com") > 0 || amazonResp.indexOf("Amazon Digital Services") > 0){
						currentPrice.setAmazonPrice(price);
						currentPrice.setAmazonPriceAmount(priceAmount);
						currentPrice.setAmazonPriceAvailable(true);
					}else{
						
						String currentThirdPriceAmount = currentPrice.getThirdPartyPriceAmount();
						if (currentThirdPriceAmount.equals("-1") || Integer.parseInt(currentThirdPriceAmount) > Integer.parseInt(priceAmount)){
							//如果现在没有第三方价格，或者从网页取得的第三方价格低于offer element里面的，以网页为准
							currentPrice.setThirdPartyPrice(price);
							currentPrice.setThirdPartyPriceAmount(priceAmount);
							currentPrice.setThirdPartyPriceAvailable(true);
						}
					}
				}
				
				
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return currentPrice;
		
	}
	
	
	public static String getPriceAmount(String formattedPrice){
		if (formattedPrice != null && formattedPrice.startsWith("$")){
			String sub = formattedPrice.substring(1);
			Double d = new Double(Double.parseDouble(sub) * 100);
			return "" + d.intValue();
		}else{
			return "-1";
		}
	}
}
